//
//  ZMAPIConfigImpl.swift
//  LeGou
//
//  Created by lxm on 2022/7/23.
//

import Foundation
class ZMAPIConfigImpl : NSObject, ZMAPIConfig {
    func filterRequest(api: ZMApiProvider, parsedModel: ZMAPIParsedModel) -> ZMAPIParsedModel {
        // 加密参数
        var pa = parsedModel
        if api.urlAndMthodAndParam().body {
            if let arrayPa = pa.param["ZMArrayParams"],let a =  AppHelper.encode(bodyParam: arrayPa) {
                pa.param = a
            }
            else if let a =  AppHelper.encode(bodyParam: pa.param) {
                pa.param = a
            }
        }
        return pa
    }
    
    func filterResponseData<T>(api: ZMApiProvider,apiParsedModel : ZMAPIParsedModel, resp: ResponseModel<T>) -> ResponseModel<T> {
        if developMode != 1 {
            // 调试工具添加数据
//            addTestTool(api: api, apiParsedModel: apiParsedModel, resp: resp)
        }
        if resp.code == .invalidToken {
            ZMAppShareData.share.clearUserInfo()
            if let tab = APPWindow?.rootViewController as? UITabBarController,let nav = tab.selectedViewController as? UINavigationController {
                if nav.children.count > 1 {
                    nav.popToRootViewController(animated: false)
                    tab.selectedIndex = 0
                }
            }
        }
        
        if resp.code == .showToast {
            ZMAlertView.show(content: resp.message, left: nil, right: "确定") {} onRight: {}
            ZMToast.hiddenActivity()
        } else if resp.code != .success {
            var canShow = true
            if let rStr = resp.realResp as? String, rStr == "Request explicitly cancelled." {
                canShow = false
                print("请求 \(api.urlAndMthodAndParam().0) 被取消")
            }
            
            if case HomeAPI.querySignPayResult = api {
                canShow = false
            }
            switch api {
                case HomeAPI.change_link, VIPMallAPI.wxCheck, HomeAPI.querySignPayResult:
                    canShow = false
                default:
                    break
            }
            if canShow {
                ZMToast.showToast(title: resp.message)
            }
        }

        return resp
    }
    
    func addTestTool<T>(api: ZMApiProvider,apiParsedModel : ZMAPIParsedModel, resp: ResponseModel<T>) {
        let url = apiParsedModel.url
        let method = apiParsedModel.httpMethod
        let pa = apiParsedModel.param
        let header = apiParsedModel.headers ?? [String : String]()
        if let r = resp.realResp {
            let j = JSON(r)
            TestNetTool.shareInstance()?.addRecordUrl(url, header: header, param: pa, method: method.rawValue, respons:j)
        }
        else {
            TestNetTool.shareInstance()?.addRecordUrl(url, header: header, param: pa, method: method.rawValue, respons: "app数据解析失败")
        }
    }
}


var sysTimeDiffer = 0.0
